{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# LangChain Expression Language(LCEL)\n",
    "LangChain Expression Language(LCEL)是LangChain的表达式语⾔，它提供了⼀种简单的⽅式来定义和执⾏任务。例如，之前与AI⼤模型交互的过程，可以⽤LCEL来表示\n"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "d8c39f162b004e9a"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "ChatOpenAI(client=<openai.resources.chat.completions.completions.Completions object at 0x0000023B44F66C80>, async_client=<openai.resources.chat.completions.completions.AsyncCompletions object at 0x0000023B44F658A0>, root_client=<openai.OpenAI object at 0x0000023B44F65690>, root_async_client=<openai.AsyncOpenAI object at 0x0000023B44F656F0>, model_name='qwen-plus', temperature=0.5, model_kwargs={}, openai_api_key=SecretStr('**********'), openai_api_base='https://dashscope.aliyuncs.com/compatible-mode/v1')"
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "# 调用大模型（阿里云百炼）\n",
    "llm = ChatOpenAI(model='qwen-plus', base_url='https://dashscope.aliyuncs.com/compatible-mode/v1', temperature=0.5)\n",
    "llm"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-07-23T03:08:20.724609Z",
     "start_time": "2025-07-23T03:08:20.707609Z"
    }
   },
   "id": "7652b2004383cae9",
   "execution_count": 3
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The weather is nice today, with gentle winds and bright sunshine.\n"
     ]
    }
   ],
   "source": [
    "# 提示词模板\n",
    "# prompt_template = ChatPromptTemplate.from_messages([\n",
    "#     ('system', 'You are a helpful assistant that translates {input_language} to {output_language}.\"'),\n",
    "#     ('user', '{text}')\n",
    "# ])\n",
    "prompt_template = ChatPromptTemplate.from_messages([\n",
    "    SystemMessagePromptTemplate.from_template(\"You are a helpful assistant that translates Chinese to {output_language}.\"),\n",
    "    HumanMessagePromptTemplate.from_template(\"{text}\")\n",
    "])\n",
    "# 结果解析器StrOutputParser会将AIMessage转换成为str，实际上就是获取AIMessage的content属性。\n",
    "parse = StrOutputParser()\n",
    "\n",
    "# 构建链\n",
    "chain = prompt_template | llm | parse\n",
    "# 直接调用链\n",
    "print(chain.invoke({'text': '今天天气不错，风和日丽的。', 'output_language': 'English'}))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-07-23T03:08:29.350787Z",
     "start_time": "2025-07-23T03:08:28.635762Z"
    }
   },
   "id": "fe44f1092e678407",
   "execution_count": 4
  },
  {
   "cell_type": "markdown",
   "source": [
    "通过LangChain的LCEL链式语法，就可以直接构建更为复杂的基于⼤模型的处理链。例如将某⼀次⼤模型调⽤的结果再次访问另⼀个⼤模型，那就只需要再chain的后⾯再链接更多的组件即可。\n",
    "\n",
    "如：我先讲上述的翻译结果出来了，我还想基于上次大模型翻译的结果进行进一步提问，要如何回复上述翻译结果。"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "e719437db03a2160"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "今天的天气确实很宜人。\n"
     ]
    }
   ],
   "source": [
    "prompt_answer = ChatPromptTemplate.from_template(\"我该如何回复这句话：{answer}，请给出10个字左右的示例。\")\n",
    "chain_answer = {'answer': chain} |prompt_answer | llm | parse\n",
    "print(chain_answer.invoke({'text': '今天天气不错，你心情怎么样？', 'output_language': 'English'}))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-07-23T03:30:06.097599Z",
     "start_time": "2025-07-23T03:30:03.748651Z"
    }
   },
   "id": "cebd0562d75048aa",
   "execution_count": 7
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
